package com.swpu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.swpu.eduservice.Listener.SubjectExcelListener;
import com.swpu.eduservice.entity.EduSubject;
import com.swpu.eduservice.entity.Excel.SubjectData;
import com.swpu.eduservice.entity.Subject.OneSubject;
import com.swpu.eduservice.entity.Subject.TwoSubject;
import com.swpu.eduservice.mapper.EduSubjectMapper;
import com.swpu.eduservice.service.EduSubjectService;
import com.swpu.servicebase.ExceptionHandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author ygq
 * @since 2021-10-15
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    /**
    * 实现功能描述：添加课程分类
    * @param
    * @return
    */
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        try {
            //1 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            EasyExcel.read(inputStream, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch(Exception e) {
            e.printStackTrace();
            throw new GuliException(20002,"添加课程分类失败");
        }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id","0");
        List<EduSubject> Onelist = baseMapper.selectList(wrapper);//查出所有的一级分类

        QueryWrapper<EduSubject> wrapper1 = new QueryWrapper<>();
        wrapper1.ne("parent_id","0");
        List<EduSubject> list = baseMapper.selectList(wrapper1); //查询出所有的二级分类

        //创建集合封装最后的数据
        List<OneSubject> res = new ArrayList<>();

        //封装一级分类
        for (EduSubject eduSubject : Onelist) {
            OneSubject one = new OneSubject();
//            one.setTitle(eduSubject.getTitle());
//            one.setId(eduSubject.getId());
//            res.add(one);
            BeanUtils.copyProperties(eduSubject,one); //快速的将一个对象的属性设置给另一个

            //在一级分类的循环中查询所有的二级分类
            List<TwoSubject> listTwo = new ArrayList<>();
            for (EduSubject subject : list) {
                if(subject.getParentId().equals(one.getId())){
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(subject,twoSubject);
                    listTwo.add(twoSubject);
                }
            }
            one.setChildren(listTwo);
            res.add(one);
        }

        return res;
    }
}
